package serv_cmd

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/proto-gen-go.git/project_member_api"
	"atomgit.com/openlinksaas/swarm_api_proxy/config"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func (apiImpl *SwarmProxyApiImpl) getTokenInfo(addr, token string) (*project_member_api.OneTimeTokenInfo, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	conn, err := grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithInitialConnWindowSize(1<<30), grpc.WithInitialWindowSize(1<<30))
	if err != nil {
		return nil, err
	}

	defer conn.Close()

	client := project_member_api.NewProjectMemberApiClient(conn)
	res, err := client.GetOneTimeToken(ctx, &project_member_api.GetOneTimeTokenRequest{
		Token: token,
	})
	if err != nil {
		return nil, err
	}
	if res.Code != project_member_api.GetOneTimeTokenResponse_CODE_OK {
		return nil, fmt.Errorf(res.ErrMsg)
	}
	return res.TokenInfo, nil
}

func (apiImpl *SwarmProxyApiImpl) existProject(ctx context.Context, c *client.Client, projectId string) (bool, error) {
	filter := filters.NewArgs()
	filter.Add("name", config.PROJECT_CONFIG_KEY+projectId)
	cfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return false, err
	}
	for _, cfgItem := range cfgItemList {
		if string(cfgItem.Spec.Data) == projectId {
			return true, nil
		}
	}
	return false, nil
}
